package cn._2dland.sakushi.client;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import cn._2dland.http.HttpClient;
import cn._2dland.http.method.GetMethod;
import cn._2dland.http.method.PostMethod;
import cn._2dland.http.method.multiparts.FilePart;
import cn._2dland.http.method.multiparts.StringPart;
import cn._2dland.sakushi.SakushiInfo;

public class XinaClient {
	private static final String USER_AGENT = "XinaBot";
	private static final int MAX_MENTION_COUNT = 200;

	private static final String MENTION_URL = "http://api.t.sina.com.cn/statuses/mentions.json";
	private static final String UPDATE_URL = "http://api.t.sina.com.cn/statuses/update.json";
	private static final String UPLOAD_URL = "http://api.t.sina.com.cn/statuses/upload.json";

	private HttpClient client = null;
	private String appKey;

	public XinaClient(String user, String pass, String key) {
		appKey = key;

		//String auth = user + ":" +  pass;
		//auth = "Basic " + Base64.encode(auth.getBytes());

		client = new HttpClient();
		client.getClientParams().setUserAgent(USER_AGENT);
		client.getClientParams().setClientCharset("utf-8");
		//client.addHeader("Authorization", auth);
	}

	/**
	 * 获取提到的消息
	 * @param sinceID
	 * @return
	 */
	public List<Mention> getMentions(String sinceID) {
		List<Mention> mentions = new ArrayList<Mention>();

		// 构造URL
		StringBuffer urlBuf = new StringBuffer(MENTION_URL);
		urlBuf.append("?source=").append(appKey).append("&count=").append(MAX_MENTION_COUNT);
		if(sinceID != null) 
			urlBuf.append("&since_id=").append(sinceID);

		GetMethod get = new GetMethod(urlBuf.toString());
		try {
			// 执行请求
			int respCode = client.executeMethod(get);
			if(respCode != HttpServletResponse.SC_OK) 
				throw new Exception("获取失败！");

			// 获取结果
			String jsonStr = get.getResponseString();
			JSONArray jsonArr = new JSONArray(jsonStr);
			for(int i=0; i<jsonArr.length(); i++) {
				Mention mention = new Mention();

				JSONObject menObj = jsonArr.getJSONObject(i);
				mention.setStatusId(menObj.getString("id"));
				mention.setSourceId(menObj.getString("in_reply_to_status_id"));
				// 获取并处理状态内容
				String text = menObj.getString("text");
				text = text.replaceAll("^@"+SakushiInfo.XINA_NAME+"\\s", "");
				text = text.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"").replaceAll("&amp;", "&");
				mention.setText(text);

				JSONObject userObj = menObj.getJSONObject("user");
				mention.setUserId(userObj.getString("id"));
				mention.setUserName(userObj.getString("name"));

				mentions.add(mention);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			// 释放资源
			get.releaseConnection();
		}
		return mentions;
	}

	/** 发布状态 */
	public String update(String feed) {
		String result = null;
		PostMethod post = new PostMethod(UPDATE_URL);
		try {
			post.addParameter("source", appKey);
			post.addParameter("status", feed);

			// 获取发送结果
			int respCode = client.executeMethod(post);
			if(respCode != HttpServletResponse.SC_OK)
				throw new Exception("发布失败！");

			// 读取结果
			result = post.getResponseString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			post.releaseConnection();
		}
		return result;
	}

	/** 发布图片 */
	public String upload(String feed, byte[] image) {
		String result = null;
		PostMethod post = new PostMethod(UPLOAD_URL);
		try {
			// 以分段的方式添加参数
			post.addPart(new StringPart("source", appKey));
			post.addPart(new StringPart("status", feed));
			// 添加图片
			FilePart fp = new FilePart("pic", "image/png", "chart.png");
			fp.readBytes(image);
			post.addPart(fp);

			// 获取发送结果
			int respCode = client.executeMethod(post);
			if(respCode != HttpServletResponse.SC_OK)
				throw new Exception("发布失败！");

			// 读取结果
			result = post.getResponseString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			post.releaseConnection();
		}
		return result;
	}
}
